package org.yi.fc.entity;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

/**
 * 角色-权限实体
 * @author ilgql
 *
 */
public class FRolePermission extends Model<FRolePermission> {

	private static final long serialVersionUID = 6991870287855294595L;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public static FRolePermission dao = new FRolePermission();
	
	private List<FRolePermission> permissions;
	
	/**
	 * 获取角色的所有权限的集合
	 * @return
	 */
	public List<FRolePermission> getPermissions(int roleId){
		StringBuffer sb = new StringBuffer();
		sb.append("select * from f_role_permission where role_id = ?");
		
		permissions = find(sb.toString(), roleId);
		
		return permissions;
	}
	
	/**
	 * 根据角色名称获取所有的权限
	 * @param roleNames
	 * @return
	 */
	public List<String> getPermissinsByRoleNames(List<String> roleNames){
		
		StringBuffer incase = new StringBuffer("(");
		if(roleNames.size() > 0){
			for(String roleName : roleNames){
				incase.append("'").append(roleName).append("' ,");
			}
		}
		
		incase.setCharAt(incase.length() - 1 , ' ');
		incase.append(")");
		
		String sql = " select name from f_permission where id in ( select permission_id from f_role_permission where role_id in ( select id from f_role where role_name in " +  incase + "))";
		return Db.query(sql);
	}
	
	/**
	 * 对角色进行授权
	 * @param roleId			角色Id
	 * @param permissionId		权限Id
	 * @param userId			用户Id
	 * @return
	 */
	public boolean grantPermission(int roleId, int permissionId, int userId){
		
		logger.debug("call grantPermission(int roleId, int permissionId, int userId) roleId={}, permissionId={}, userId={}",roleId, permissionId, userId);
		
		boolean result = false;
		
		FSysUser user = FSysUser.dao.findById(userId);
		FRole role = FRole.dao.findById(roleId);
		FPermission permission = FPermission.dao.findById(permissionId);
		
		if(user == null){
			logger.error("对角色进行授权时，根据授权人userId={}无法找到授权人", userId);
			return false;
		}
		
		if(role == null){
			logger.error("对角色进行授权时，根据角色的roleId={}无法找到该角色。", roleId);
			return false;
		}
		
		if(permission == null){
			logger.error("对角色进行授权时，根据权限的permissionId={}无法找到该权限。", permissionId);
			return false;
		}
		
		try{
			result = new FRolePermission()
			.set("role_id", roleId)
			.set("permission_id", permissionId)
			.set("crate_user_id", userId)
			.set("create_time", new Date())
			.save();
		}catch(Exception e){
			logger.error("用户【{}】对角色【{}】进行授权【{}】失败,失败原因：\n", userId, roleId, permissionId,e);
		}
		
		return result;
	}
	
	/**
	 * 根据角色ID和权限ID获取授权记录
	 * @param roleId				角色id
	 * @param permissionId			权限id
	 * @return						FRolePermissions
	 */
	public FRolePermission getRolePermissions(int roleId, int permissionId){
		String sql = "select * from f_role_permission where role_id =? and permission_id = ?";
		return findFirst(sql,roleId,permissionId);
	}
	
	/**
	 * 根据角色Id获取角色所拥有的权限
	 * @param roleId				角色id
	 * @return						List<FPermission>
	 */
	public List<FPermission> getPermission(int roleId){
		String sql = "select * from f_permission where id in (  select role_id from f_role_permission where role_id = ? )";
		List<FPermission> list = Db.query(sql, roleId);
		return list;
	}
	
	/**
	 * 取消授权
	 * @param roleId			角色Id
	 * @param permissionId		权限Id
	 * @return        			是否取消成功
	 */
	public boolean cancleGrant(int roleId, int permissionId){
		boolean result = false;
		FRolePermission rolePermission = getRolePermissions(roleId, permissionId);
		
		if(rolePermission == null){
			logger.error("根据【角色ID={}】和【权限ID={}】获取授权记录为空，无法取消不存在的授权记录。", roleId, permissionId);
		}else{
			try{
				result = rolePermission.delete();
			}catch(Exception e){
				logger.error("根据【角色ID={}】和【权限ID={}】取消授权（即删除授权记录）失败，失败原因：\n", roleId, permissionId,e);
			}
		}
		
		return result;
	}
	
}
